<template>
  <div id="addPicturePage">
    <h2 style="margin-bottom: 16px">
      {{ route.query?.id ? '编辑图片' : '创建图片' }}
    </h2>
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至空间：<a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
    </a-typography-paragraph>
    <a-tabs v-if="!route.query?.id" v-model:active-key="uploadType">
      <a-tab-pane key="file" tab="本地文件上传">
        <PictureUpload :picture="picture" :onSuccess="onSuccess" :spaceId="spaceId" />
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL 上传">
        <UrlPictureUpload :picture="picture" :onSuccess="onSuccess" :spaceId="spaceId" />
      </a-tab-pane>
    </a-tabs>
    <PictureUpload v-else :picture="picture" :onSuccess="onSuccess" />
    <!-- 图片编辑 -->
    <div v-if="picture" class="edit-bar">
      <a-space size="middle">
        <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
        <a-button class="aiBtn" :icon="h(FullscreenOutlined)" @click="doImagePainting"
          >Ai扩图</a-button
        >
        <ImageCropper
          ref="imageCropperRef"
          :imageUrl="picture?.url"
          :picture="picture"
          :spaceId="spaceId"
          :space="space"
          :onSuccess="onCropSuccess"
        />
        <ImageOutPainting
          ref="imageOutPaintingRef"
          :picture="picture"
          :spaceId="spaceId"
          :onSuccess="onImageOutPaintingSuccess"
        />
      </a-space>
    </div>
    <!--    输入图片信息功能-->
    <a-form v-if="picture" layout="vertical" :model="pictureForm" @finish="handleSubmit">
      <a-form-item label="名称" name="name">
        <a-input v-model:value="pictureForm.name" placeholder="请输入图片名" />
      </a-form-item>
      <a-form-item label="简介" name="introduction">
        <a-textarea
          v-model:value="pictureForm.introduction"
          placeholder="请输入简介"
          :rows="2"
          autoSize
          allowClear
        />
      </a-form-item>
      <a-form-item label="分类" name="category">
        <a-auto-complete
          v-model:value="pictureForm.category"
          :options="categoryOptions"
          placeholder="请输入分类"
          allowClear
        />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="pictureForm.tags"
          :options="tagOptions"
          mode="tags"
          placeholder="请选择或输入标签"
          :max-tag-count="3"
          allowClear
          @search="handleTagSearch"
          @change="handleTagChange"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">
          {{ route.query?.id ? '更新图片' : '创建图片' }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script setup lang="ts">
import PictureUpload from '@/components/PictureUpload.vue'
import {computed, onMounted, reactive, ref, h, watchEffect} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController'
import { message } from 'ant-design-vue'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import ImageCropper from '@/components/ImageCropper.vue'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import ImageOutPainting from '@/components/ImageOutPainting.vue'
import {getSpaceVoByIdUsingGet} from "@/api/spaceController";

const router = useRouter()
const route = useRoute()

const picture = ref<API.PictureVO>() // 图片对象
const pictureForm = reactive<API.PictureEditRequest>({}) // 表单对象

//定义上传图片方法，本地文件和url上传
const uploadType = ref<'file' | 'url'>('file')

// 传入子组件参数
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}
// 空间id，表示上传到哪个空间，null为上传到公共
const spaceId = computed(() => {
  return route.query?.spaceId
})

/**
 * 提交表单函数
 * @param values
 */
const handleSubmit = async (values: any) => {
  // 拿到图片id，如果数据库不存在，退出
  const pictureId = picture.value?.id
  if (!pictureId) return
  // 后端接收结果，解析values（即表单内容）
  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: spaceId.value,
    ...values,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('图片操作成功')
    //跳转到图片详情页
    router.push({
      path: `/picture/${pictureId}`,
    })
  } else {
    message.error('图片操作失败，' + res.data.message)
  }
}

/**
 * 分类和标签输入补充选项数据
 */
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])

// 获取标签和分类选项
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    //转换成下拉选项组件接受的格式
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})

/**
 * 图片信息修改
 */
// 获取旧数据
const getOldPicture = async () => {
  const id = route.query?.id
  if (id) {
    const res = await getPictureVoByIdUsingGet({
      id: id,
    })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.category = data.category
      pictureForm.tags = data.tags
    }
  }
}

onMounted(() => {
  getOldPicture()
})

/**
 * 处理标签限制
 */
// 是否已达到最大标签数
const isTagsFull = computed(() => pictureForm.tags.length >= 3);

// 处理标签变化
const handleTagChange = (newTags) => {
  if (newTags.length > 3) {
    pictureForm.tags = newTags.slice(0, 3);
    message.error('最多只能有三个标签');
  }
};

// 处理标签输入
const handleTagSearch = (inputValue, { prefixCls, setOpen }) => {
  if (isTagsFull.value) {
    message.error('已达到最大标签数量');
    setOpen(false);
    return;
  }
}

/**
 * 图片编辑弹窗
 */
// 图片编辑弹窗引用
const imageCropperRef = ref()

// 编辑图片
const doEditPicture = () => {
  if (imageCropperRef.value) {
    imageCropperRef.value.openModal()
  }
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

/**
 * Ai 扩图相关函数
 */
// AI 扩图弹窗引用
const imageOutPaintingRef = ref()

// AI 扩图
const doImagePainting = () => {
  if (imageOutPaintingRef.value) {
    imageOutPaintingRef.value.openModal()
  }
}

// 编辑成功事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}
/**
 * 获取空间信息
 */
const space = ref<API.SpaceVO>()
const fetchSpace = async () => {
  // 获取数据
  if (spaceId.value) {
    const res = await getSpaceVoByIdUsingGet({
      id: spaceId.value,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    }
  }
}

watchEffect(() => {
  fetchSpace()
})
</script>
<style scoped>
:root {
  --primary: #6366f1;
  --secondary: #a855f7;
  --accent: #ec4899;
}

#addPicturePage {
  max-width: 720px;
  margin: 0 auto;
}

#addPicturePage .edit-bar {
  text-align: center !important;
  margin: 16px 0;
}

#addPicturePage :deep(.aiBtn.ant-btn) {
  border: none;
  border-radius: 12px !important;
  background-image: linear-gradient(120deg, #fccb90 0%, #d57eeb 100%);
  overflow: hidden;
  transition: transform 0.3s ease !important;
  color: white;
}
</style>
